package com.browsesoft.adapter;

import java.util.LinkedList;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.w3c.dom.Document;
import org.w3c.dom.Element;

import com.browsesoft.ExtendElement;
import com.browsesoft.arrange.Arrange;
import com.browsesoft.dbtools.DBTools;
import com.browsesoft.htmlcomponent.HTMLDBTableModel;
import com.browsesoft.workflow.support.sortInterface;

public class ArrangeDBTableModel extends HTMLDBTableModel implements
		sortInterface {
	/**
	 * 查看，编辑，修改的权利
	 */
	LinkedList right = new LinkedList();

	/**
	 * 初始化model
	 * 
	 * @throws Exception
	 */

	public void init(HttpServletRequest request) throws Exception {
		super.init(request);
		// 从页面查找页面需要的列
		this.findColTypeFromPage();
	}

	/**
	 * 设置传递的参数
	 * 
	 * @param request
	 */
	public void service(HttpServletRequest request, HttpServletResponse response)
			throws Exception {
		// 得到条件
		String condition = request.getParameter("condition");
		if (parentID == null) {
			parentID = request.getParameter("point");
		}
		// 有必备条件
		if (parentID != null) {
			Arrange arrange = Arrange.getArrange(parentID);
			while (arrange != null) {
				String str = arrange.getName();
				// 只有不是根，才加上字段条件
				if (!arrange.isRoot()) {
					String fieldName = arrange.getFieldName();
					if (sql.indexOf("where") == -1) {
						sql += " where " + fieldName + "=\'" + str + "\' and ";
					} else {
						sql += fieldName + "=\'" + str + "\' and ";
					}
				}
				arrange = arrange.getGranddad();
			}
			// 去掉最后一个“and ”
			sql = sql.substring(0, sql.length() - 4);
			// 补上用户输入的条件
			if (condition != null && !condition.equals("")) {
				sql += " and " + condition;
			}
			// 将parentID清空
			parentID = null;
		}
		// 没有必备条件
		else {
			// 添加用户输入的条件
			if (condition != null && !condition.equals("")) {
				sql += " where " + condition;
			}
		}
		// 得到结果
		datas = DBTools.executeQueryWithTableHead(sql);
		String tt = request.getParameter(component.getName().concat(".sort"));
		if (tt != null) {
			 String temp = tt.substring(tt.lastIndexOf(".") + 1);
			if (!((sortInterface) this).getOrderBy()) {
				((sortInterface) this).sort(temp);
				((sortInterface) this).setOrderBy();
			} else if (((sortInterface) this).getOrderBy()) {
				((sortInterface) this).reverseSort(temp);
				((sortInterface) this).setOrderBy();
			}
		}
	}

	/**
	 * 得到列数
	 * 
	 * @return 列数
	 */
	public int getColumnCount() {
		return cnames.size() + right.size();
	}

	/**
	 * 得到某列的操作类型
	 * 
	 * @return 类型
	 */
	public String getType(int col) {
		if (col < cnames.size()) {
			return "td";
		}
		// 取得合适的类型
		else if (col >= cnames.size() && col < cnames.size() + right.size()) {
			return (String) right.get(col - cnames.size());
		}
		return null;
	}

	public void modifyCellValue(Element td, Document doc, int row, int col) {
		try {
			// 找到id所在的位置
			int IDindex = 0;
			for (int i = 0; i < datas[0].length; i++) {
				if (datas[0][i].toLowerCase().equals("id")) {
					IDindex = i;
				}
			}
			// 显示其他
			if (col < cnames.size()) {
				// 得到链接
				LinkedList nl = ExtendElement.findElements(td, "type", "link");
				if (nl.size() != 0) {
					Element link = (Element) nl.get(0);
					String value = link.getAttribute("onclick");
					value = value.replaceAll("point=", "point="
							+ datas[row + 1][0]);
					link.setAttribute("onclick", value);
				}
				int index = DBTools.indexOf(datas[0], (String) enames.get(col));
				if (index != -1) {
					ExtendElement.replaceElementContext(td, doc
							.createTextNode(datas[row + 1][index]));
				} else {
					ExtendElement.replaceElementContext(td, doc
							.createTextNode(""));
				}
			}
			// 详细信息
			else if (getType(col).equals("detail")) {
				Element e = (Element) ExtendElement.findElements(td, "type",
						"link").get(0);
				String str = e.getAttribute("onclick");
				str = str.replaceAll("id=", "id=" + datas[row + 1][IDindex]);
				str = str.replaceAll("templatename=", "templatename=" + form);
				e.setAttribute("onclick", str);
			}
			// 修改
			else if (getType(col).equals("modify")) {
				Element e = (Element) ExtendElement.findElements(td, "type",
						"link").get(0);
				String str = e.getAttribute("onclick");
				str = str.replaceAll("id=", "id=" + datas[row + 1][IDindex]);
				str = str.replaceAll("templatename=", "templatename=" + form);
				e.setAttribute("onclick", str);
			}
			// 删除
			else if (getType(col).equals("delete")) {
				Element e = (Element) ExtendElement.findElements(td, "type",
						"link").get(0);
				String str = e.getAttribute("onclick");
				str = str.replaceAll("id=", "id=" + datas[row + 1][IDindex]);
				// 设置删除的表名
				str = str.replaceAll("tablename=", "tablename=" + tableName);
				e.setAttribute("onclick", str);
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	/**
	 * 从页面查找页面需要的列
	 */
	public void findColTypeFromPage() {
		// 找详细信息的列
		LinkedList list = ExtendElement.findElements(this.component
				.getElement(), "type", "detail");
		// 如果需要详细信息
		if (list.size() > 0) {
			right.add("detail");
		}
		// 找修改的列
		list = ExtendElement.findElements(this.component.getElement(), "type",
				"modify");
		// 如果需要修改的列
		if (list.size() > 0) {
			right.add("modify");
		}
		// 找删除的列
		list = ExtendElement.findElements(this.component.getElement(), "type",
				"delete");
		// 如果需要删除的列
		if (list.size() > 0) {
			right.add("delete");
		}
	}
}